﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.Utilities;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.ModelService;

namespace RN.ERP.Web.Person
{
    public partial class PersonEmpWorkInfo : BasePage
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParams();
            }
        }

        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams()
        {
            Guid empGuid = Guid.Empty;
            int workId =0;
            if (!string.IsNullOrEmpty(Request.QueryString["empGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["empGuid"], out empGuid))
                {
                    hdEmpGuid.Value = empGuid.ToString();
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["workId"]))
            {
                if (int.TryParse(Request.QueryString["workId"], out workId))
                {
                    hdStatus.Value = "1";
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["corpName"]))
            {
                hidCorpName.Value = Request.QueryString["corpName"];
            }
            hdID.Value = workId.ToString();
            ////异步调用方法
            if (Request.Params["action"] != null)
            {
                string action = Request.Params["action"];
                switch (action)
                {
                    case "WorkExpAdd":
                        WorkExpSave(true, empGuid);
                        break;
                    case "WorkExpEdit":
                        WorkExpSave(false, empGuid);
                        break;
                    case "GetWorkExp":
                        GetWorkExp(empGuid.ToString(), workId.ToString());
                        break;
                 
                }
            }
        }

        /// <summary>
        ///查询信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="AreaCode"></param>
        private void GetWorkExp(string empGuid, string workId)
        {
            int workId1 = 0;
            int.TryParse(workId, out workId1);
            Guid empGuid1 = Guid.Empty;
            Guid.TryParse(empGuid, out empGuid1);
            if (empGuid1 == Guid.Empty || workId1==0)
            {
                var result1 = "{\"result\":1,\"message\":\"参数错误！\"}";
                OutputData(result1);
                return;
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var WorkExp = JsonConvert.DeserializeObject<List<ModelService.tb_WorkExperience>>(client.GetWorkExperienceList(empGuid, UserInfo.CurrentArea));
                if (WorkExp != null)
                {
                    var query = JsonConvert.SerializeObject(WorkExp.Where(q => q.ID == workId1).FirstOrDefault());
                    var result = "{\"result\":0,\"data\":" + query + "}";
                    OutputData(result);
                }

            }
        }

        /// <summary>
        /// 添加修改信息
        /// </summary>
        private void WorkExpSave(bool flag, Guid empGuid)
        {
            if (empGuid == Guid.Empty)
            {
                OutputData("{\"Result\":false,\"Message\":\"请先添加人员！\"}");
                return;
            }
            if (Request.Params["data"] == null)
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            string data = Request.Params["data"];//取得客户端提交的数据
            //转化数据对象
            var managers = JsonConvert.DeserializeObject<List<JsonEntity>>(Request.Params["data"]);
            ModelService.tb_WorkExperience empWork = null;
            foreach (var manager in managers)
            {
                var valStr = manager.value.Trim('\"');//对象值为json格式的tb_WorkExperience对象
                empWork = JsonConvert.DeserializeObject<ModelService.tb_WorkExperience>(valStr);
            }
            if (empWork != null)
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string result = "";
                    string corpGuid = UserInfo.CorpUserGuid;
                    //执行添加或修改操作
                    if (flag)
                    {
                        result = client.WorkExperienceAdd(JsonConvert.SerializeObject(empWork), UserInfo.CurrentArea);
                        
                    }
                    else
                    {
                        result = client.WorkExperienceEdit(JsonConvert.SerializeObject(empWork), UserInfo.CurrentArea);
                    }
                    if (SystemID == "95")
                    {
                        ZhuanjiaLihaiDwCheck(result, empWork, flag);
                    }
                    OutputData(result);
                }
            }
        }

        #region  专家利害关系操作

        /// <summary>
        /// 添加修改专家厉害单位
        /// </summary>
        /// <param name="empWork"></param>
        private void ZhuanjiaLihaiDwCheck(string result,ModelService.tb_WorkExperience empWork,bool flag)
        {
            var result0 = JsonConvert.DeserializeObject<ModelService.OperationResult>(result);
            if (!result0.Result)
            {
                return;
            }
            if (empWork==null || empWork.EndDate==null)
            {
                return;
            }
            DateTime dt = DateTime.Now;
            DateTime EndDate;
            if (empWork.EndDate != "至今")
            {
                DateTime.TryParse(empWork.EndDate, out EndDate);
                int year = EndDate.Year;
                int month = EndDate.Month;
                if (dt.Year - year > 3)
                {
                    return;
                }
                if (dt.Year - year == 3 && month <= dt.Month)
                {
                    return;
                }
            }
            if (flag)
            {
                ZhuanjiaLihaiDwAdd(empWork.EmpGuid.ToString(), empWork.CorpName, UserInfo.CurrentArea);
            }
            else
            {
                ZhuanjiaLihaiDwEdit(empWork.EmpGuid.ToString(), empWork.CorpName, UserInfo.CurrentArea);
            }
        }

        /// <summary>
        /// 添加专家利害单位
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="entityName"></param>
        /// <param name="areaCode"></param>
        private void ZhuanjiaLihaiDwAdd(string empGuid, string entityName, string areaCode)
        {
            try
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    ModelService.tb_User_Relation model = new ModelService.tb_User_Relation();
                    model.Gid = Guid.NewGuid();
                    model.ID = 0;
                    model.UserGuid = Guid.Parse(empGuid);////empguid
                    model.CreateTime = DateTime.Now;
                    model.EntityFlag = 1;
                    model.EntityGuid = Guid.NewGuid();
                    model.EntityName = entityName;////企业名称
                    model.AreaCode = areaCode;
                    model.AppId = 95;
                    model.Reason = "近三年工作单位";
                    model.ClassId = 1002;
                    var result = client.SaveUserRelationInfo(JsonConvert.SerializeObject(model), areaCode);
                }
            }
            catch { }
        }

        /// <summary>
        /// 修改专家利害单位
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="entityName"></param>
        /// <param name="areaCode"></param>
        private void ZhuanjiaLihaiDwEdit(string empGuid, string entityName, string areaCode)
        {
            try
            {
                string corpName = string.Empty;
                if (Request.Params["workCorp"] != null)
                {
                    corpName = Request.Params["workCorp"].Trim();
                }
                if (corpName != entityName.Trim())
                {
                    using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                    {
                        var result = client.UpdateUserRelationCorp(empGuid, 1002, corpName, entityName.Trim(), areaCode);
                    }
                }
            }
            catch { }
        }

        #endregion

        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }
    }
}
